<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="88px"
    >
      <el-form-item label="客户名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="客户编号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入客户编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="管理单元" prop="manageUnit">
        <el-input
          v-model="queryParams.manageUnit"
          placeholder="请输入管理单元"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="所属区域" prop="area">
        <el-cascader
          v-model="queryParams.area"
          :options="areaList"
          :props="defaultProps"
          class="!w-240px"
          clearable
          filterable
          placeholder="请选择所属区域"
        />
      </el-form-item>
      <el-form-item label="联系人姓名" prop="contactName">
        <el-input
          v-model="queryParams.contactName"
          placeholder="请输入联系人姓名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="contactNumber">
        <el-input
          v-model="queryParams.contactNumber"
          placeholder="请输入联系电话"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['san:biz-customer-archive:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['san:biz-customer-archive:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
          type="danger"
          plain
          :disabled="isEmpty(checkedIds)"
          @click="handleDeleteBatch"
          v-hasPermi="['san:biz-customer-archive:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      row-key="id"
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="客户名称" align="center" prop="name" />
      <el-table-column label="客户编号" align="center" prop="code" />
      <el-table-column label="管理单元" align="center" prop="manageUnit" />
      <el-table-column label="地址" align="center" prop="address" />
      <el-table-column label="联系人姓名" align="center" prop="contactName" />
      <el-table-column label="联系电话" align="center" prop="contactNumber" />
      <el-table-column label="服务状态" align="center" prop="serviceStatus">
        <template #default="scope">
          <span v-if="scope.row.serviceStatus === '0'">暂停</span>
          <span v-if="scope.row.serviceStatus === '1'">服务中</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['san:biz-customer-archive:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['san:biz-customer-archive:delete']"
          >
            删除
          </el-button>
          <el-button
            v-if="scope.row.serviceStatus === '1'"
            link
            type="danger"
            @click="changeServiceStatus(scope.row.id, '0')"
            v-hasPermi="['san:biz-customer-archive:update']"
          >
            停止服务
          </el-button>
          <el-button
            v-if="scope.row.serviceStatus === '0'"
            link
            type="primary"
            @click="changeServiceStatus(scope.row.id, '1')"
            v-hasPermi="['san:biz-customer-archive:update']"
          >
            恢复服务
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <CustomerArchiveForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { CustomerArchiveApi, CustomerArchive } from '@/api/biz/customer'
import CustomerArchiveForm from './CustomerArchiveForm.vue'
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import { defaultProps, handleTree, treeToString } from '@/utils/tree'
import * as AreaApi from '@/api/system/area'

/** 客户档案 列表 */
defineOptions({ name: 'CustomerArchive' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<CustomerArchive[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  code: undefined,
  preName: undefined,
  manageUnit: undefined,
  area: undefined,
  position: undefined,
  address: undefined,
  industry: undefined,
  contactName: undefined,
  contactNumber: undefined,
  contactDuty: undefined,
  contactAge: undefined,
  introduce: undefined,
  businessSource: undefined,
  companyScale: undefined,
  customerRequire: undefined,
  powerScene: undefined,
  signDifficulty: undefined,
  receiveDifficulty: undefined,
  directorName: undefined,
  directorNumber: undefined,
  directorDuty: undefined,
  directorAge: undefined,
  powerIndustryKnown: undefined,
  powerKnowledge: undefined,
  specialRemark: undefined,
  createTime: [],
  ownerUserId: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const areaList = ref([]) // 地区列表

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await CustomerArchiveApi.getCustomerArchivePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 查询列表 */
const getAreaList = async () => {
  // 获得地区列表
  areaList.value = await AreaApi.getAreaTree()
  console.log(areaList.value)
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await CustomerArchiveApi.deleteCustomerArchive(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除客户档案 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await CustomerArchiveApi.deleteCustomerArchiveList(checkedIds.value)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: CustomerArchive[]) => {
  checkedIds.value = records.map((item) => item.id)
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await CustomerArchiveApi.exportCustomerArchive(queryParams)
    download.excel(data, '客户档案.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const changeServiceStatus = async (id: number, serviceStatus: string) => {
  const data = {
    id: id,
    serviceStatus: serviceStatus
  } as unknown as CustomerArchive
  await message.confirm('是否确认变更服务状态?')
  await CustomerArchiveApi.changeServiceStatus(data)
  await getList()
}

/** 初始化 **/
onMounted(() => {
  getAreaList()
  getList()
})
</script>
